import {Component, OnInit} from '@angular/core';
import * as moment from 'moment';
import {OrderService} from '../order.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {AliyunOssOutputUrl, appletApiUrl} from 'config/api';
import {Router, NavigationEnd} from '@angular/router';
import {LocalStorageService} from '../../../lib/service/local-storage.service';

@Component({
  selector: 'app-order',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
  providers: [OrderService]
})
export class ListComponent implements OnInit {

  sliderWidth = 180;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  isCollapsed = false;
  order_type = 0; // 订单类型 0  全部 1普通 2拼团
  type = '0'; // 订单状态 0全部 1待付款 2待发货 3待收货 4交易完成 5售后
  searchOpen = false;
  _startDate = null;
  _endDate = null;
  startDate = null;
  endDate = null;
  order_no: string;
  goods_name: string;
  phone;
  nick_name: string;
  order_time = [null, null];
  progress_width = 50;

  _allChecked = false;
  _indeterminate = false;
  sortMap = {};
  loading = false;
  checkedIds = [];
  total;
  page = 1;
  pageSize = 10;
  listData = [];

  refundModalVisible = false; // 退款弹窗
  refund_info;
  refund_remark;


  _startValueChange = () => {
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  }
  _endValueChange = () => {
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  }
  _disabledStartDate = (startValue) => {
    if (!startValue || !this._endDate) {
      return false;
    }
    return startValue.getTime() >= this._endDate.getTime();
  }
  _disabledEndDate = (endValue) => {
    if (!endValue || !this._startDate) {
      return false;
    }
    return endValue.getTime() <= this._startDate.getTime();
  }
  shopid: any;

  toggleCollapsed(value) {
    this.isCollapsed = value;
  }

  constructor(private orderService: OrderService,
              private _message: NzMessageService,
              private confirmServ: NzModalService,
              private router: Router,
              private localStorageService: LocalStorageService
  ) {

    this.router.events.filter(event => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {
      if (this.shopid !== this.localStorageService.getShop()['id']) {
        this.shopid = this.localStorageService.getShop()['id'];
        this.getOrderList();
      }
    });
  }

  ngOnInit() {
    this.getOrderList();
  }

  orderType = {
    "1": "普通订单",
    "2": "普通拼团",
    "3": "抽奖拼团",
    "4": "团长免单",
    "5": "推客免单"
  }

  prizeType = {
    "0": "待开奖",
    "1": "开奖成功",
    "2": "开奖失败"
  }
  winType = {
    "0": "未中奖",
    "1": "一等奖",
    "2": "二等奖",
    "3": "三等奖",
    "4": "四等奖",
    "5": "五等奖"
  }
  expressType = {
    "1": "待发货",
    "2": "待收货",
    "3": "配送中",
    "4": "交易完成",
    "5": "申请退款",
    "6": "已退货"
  }
  refundType = {
    "1": "申请退款",
    "2": "同意退款",
    "4": "退款失败",
    "7": "处理中"
  }

  getOrderList() {
    this._allChecked = false;
    this._indeterminate = false;
    this.loading = true;
    this.orderService.getOrderList(
      this.shopid,
      this.order_no,
      this.nick_name,
      this.goods_name,
      this.phone,
      this.order_type,
      this.type,
      this.startDate,
      this.endDate,
      this.page,
      this.pageSize,
      JSON.stringify(this.sortMap)
    ).subscribe(res => {
      this.loading = false;
      if (res.code === 200) {
        this.total = res.data.total;
        this.listData = res.data.data;
        this.total = res.data.total;
        const listData = res.data.data;
        let checkedNumber = 0;
        let order_type = this.orderType;
        let prizeType = this.prizeType;
        let winType = this.winType;
        let expressType = this.expressType;
        let refundType = this.refundType;
      } else {
        this._message.create('error', res.message);
      }
    });
  }


  keyDown(e) {
    e.code === 'Enter' ? this.search() : '';
  }

  search() {
    if (!this.searchOpen) {
      this.startDate = '';
      this.endDate = '';
      this.phone = '';
    } else {
      this.startDate = this._startDate ? moment(this._startDate).format('YYYY-MM-DD 00:00:00') : '';
      this.endDate = this._endDate ? moment(this._endDate).format('YYYY-MM-DD 23:59:59') : '';
    }
    this.page = 1;
    this.getOrderList();
  }

  reset() {
    this.order_no = '';
    this.goods_name = '';
    this.nick_name = '';
    this._startDate = '';
    this._endDate = '';
    this.startDate = '';
    this.endDate = '';
    this.phone = '';
  }

  _refreshStatus(e?, id?) {
    event.stopPropagation();
    if (e) {
      this.checkedIds.push(id);
    } else {
      this.checkedIds.every((val, idx, array) => {
        if (id === val) {
          this.checkedIds.splice(idx, 1);
          return false;
        }
        return true;
      });
    }
    const allChecked = this.listData.every(value => value.checked === true);
    const allUnChecked = this.listData.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  };

  _checkAll(value) {
    if (value) {
      this.listData.every((val, idx, array) => {
        if (!val.checked) {
          val.checked = true;
          this.checkedIds.push(val.id);
        }
        return true;
      });
    } else {
      this.listData.every((val, idx, array) => {
        if (val.checked) {
          val.checked = false;
          this.checkedIds.every((val1, idx1, array1) => {
            if (val.id === val1) {
              this.checkedIds.splice(idx1, 1);
              return false;
            }
            return true;
          });
        }
        return true;
      });
    }
    this._refreshStatus();
  };

  sort(sortName, value) {
    if (value) {
      console.log(value);
      this.sortMap[sortName] = value.slice(0, -3);
    } else {
      delete this.sortMap[sortName];
    }
    this.getOrderList();
  }

  changeOrderType(type) {
    if (type === this.type) return;
    this.checkedIds = [];
    this.type = type;
    this.page = 1;
    this.getOrderList();
  }

  turnParse(str) {
    return JSON.parse(str);
  }

  // 处理退款
  dealRefund(data) {
    this.refund_info = null;
    this.orderService.getRefundReason().subscribe(rs => {
      // console.log(rs);
      this.orderService.getRefundOrder(data.id).subscribe(res => {
        // console.log(res);
        this.refund_info = res.data;
        this.refund_info.refund_reason_remark = '';

        for (const v in rs.data) {
          if (parseInt(v, 10) === this.refund_info.refund_reason) {
            this.refund_info.refund_reason_remark = rs.data[v];
          }
        }
      });
    });
    this.refundModalVisible = true;
  }

  // 同意退款
  agreeRefund() {
    this.orderService.agreeRefund(this.refund_info.order_sub_id, this.refund_remark).subscribe(res => {
      if (res.code === 2000) {
        this.refundModalVisible = false;
        this.getOrderList();
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  // 拒绝退款
  refuseRefund() {
    this.orderService.refuseRefund(this.refund_info.order_sub_id, this.refund_remark).subscribe(res => {
      if (res.code === 2000) {
        this.refundModalVisible = false;
        this.getOrderList();
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  // 按勾选结果导出
  exportChecked(type) {  // type 1: 全部导出 2: 勾选导出
    if (type === 2 && !this.checkedIds.length) {
      this.confirmServ.error({
        title: '下载订单失败',
        content: '您未勾选任何订单，请勾选需要下载的订单'
      });
      return;
    }
    let data;
    if (type === 1) {
      this.startDate = this._startDate ? moment(this._startDate).format('YYYY-MM-DD 00:00:00') : '';
      this.endDate = this._endDate ? moment(this._endDate).format('YYYY-MM-DD 23:59:59') : '';
      data = {
        order_no: this.order_no,
        nick_name: this.nick_name,
        goods_name: this.goods_name,
        order_type: this.order_type,
        type: this.type,
        start_time: moment(this.startDate, 'YYYY-MM-DD HH:mm:ss').valueOf() / 1000,
        end_time: moment(this.endDate, 'YYYY-MM-DD HH:mm:ss').valueOf() / 1000,
        // start_time: this.startDate,
        // endTime: this.endDate,
        page: 1,
        pageSize: 999
      };
    } else {
      data = {ids: JSON.stringify(this.checkedIds)};
    }
    const link = document.createElement('a');
    this.orderService.down_xsl(data).subscribe(res => {
      link.setAttribute('href', window.URL.createObjectURL(res));
      const now = moment().format('YYYY-MM-DD h:mm:ss');
      link.setAttribute('download', '订单' + now + '.xls');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }
}
